import {ref} from 'vue'
import {defineStore} from 'pinia'


export const useHistoryStore = defineStore('history', () => {
    
    const history = ref([])

    const add = (item) => {
      // 如果数组中没有内容
      if (history.value.length === 0) {
        history.value[0] = item
      }
      // 去重
      for (let i = 0; i < history.value.length; i++) {
        const each = history.value[i]
        if ( each.novelId === item.novelId ){
          history.value.splice(i,1)
        }
      }
      // 限制游览记录
      if(history.value.length > 50) {
        history.value.pop()
      }
      // 首位添加
      history.value.unshift(item)
    }

    const remove = (novelId) => {
      history.value = history.value.filter(item => item.novelId != novelId)
    }

    return {
     history,
     add,
     remove
    }
  },
  {
    persist: {
      key: "history",
      storage: localStorage,
      // paths:['fontSize','isGreen','isDark'],
      // paths: ["token", "loginUserInfo"],
      serializer: {
        deserialize: JSON.parse,
        serialize: JSON.stringify,
      },
    }
  }
)
